/**
 * @Description
 * @Author LZL
 * @Date 2025/2/25
 */


package com.kcb.coursemanager;

import com.kcb.connectDB.connectDB;
import com.kcb.choose.choose2;

import javax.swing.*;
import java.awt.*;
import java.sql.*;

public class modifycourse extends JFrame {
    private JTextField courseNameField, teacherNameField, timeField, locationField;
    private JButton updateButton, backButton;
    private String username;
    private connectDB dbConnector;

    public modifycourse(String username) {
        this.username = username;
        this.dbConnector = new connectDB();

        setTitle("城科课程表管理系统:课程表修改功能");
        setSize(500, 350);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        ImageIcon icon = new ImageIcon("C:\\Users\\TBS\\IdeaProjects\\KCB\\image\\ccst.png");
        if (icon != null) {
            setIconImage(icon.getImage());
        } else {
            System.out.println("Failed to load icon image.");
        }

        // 设置主面板
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setBackground(new Color(240, 245, 255));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel titleLabel = new JLabel("修改课程信息");
        titleLabel.setFont(new Font("宋体", Font.BOLD, 22));
        titleLabel.setForeground(new Color(50, 90, 180));

        courseNameField = createStyledTextField();
        teacherNameField = createStyledTextField();
        timeField = createStyledTextField();
        locationField = createStyledTextField();

        updateButton = createStyledButton("更新课程", new Color(50, 150, 50));
        backButton = createStyledButton("返回", new Color(120, 120, 120));

        // 布局
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(titleLabel, gbc);

        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;

        addLabel(panel, gbc, "课程名称:", 1);
        addTextField(panel, gbc, courseNameField, 1);

        addLabel(panel, gbc, "教师名称:", 2);
        addTextField(panel, gbc, teacherNameField, 2);

        addLabel(panel, gbc, "时间:", 3);
        addTextField(panel, gbc, timeField, 3);

        addLabel(panel, gbc, "地点:", 4);
        addTextField(panel, gbc, locationField, 4);

        gbc.gridy = 5;
        gbc.gridx = 0;
        panel.add(backButton, gbc);

        gbc.gridx = 1;
        panel.add(updateButton, gbc);

        getContentPane().add(panel);

        // 事件监听
        updateButton.addActionListener(e -> updateCourse());
        backButton.addActionListener(e -> {
            new choose2(username).setVisible(true);
            dispose();
        });
    }

    private void addLabel(JPanel panel, GridBagConstraints gbc, String text, int y) {
        gbc.gridx = 0;
        gbc.gridy = y;
        panel.add(new JLabel(text), gbc);
    }

    private void addTextField(JPanel panel, GridBagConstraints gbc, JTextField textField, int y) {
        gbc.gridx = 1;
        gbc.gridy = y;
        panel.add(textField, gbc);
    }

    private JTextField createStyledTextField() {
        JTextField textField = new JTextField(15);
        textField.setFont(new Font("宋体", Font.PLAIN, 16));
        textField.setPreferredSize(new Dimension(180, 30));
        return textField;
    }

    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("宋体", Font.BOLD, 16));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setPreferredSize(new Dimension(180, 45));
        return button;
    }

    private void updateCourse() {
        String courseName = courseNameField.getText().trim();
        String teacherName = teacherNameField.getText().trim();
        String time = timeField.getText().trim();
        String location = locationField.getText().trim();

        if (courseName.isEmpty() || teacherName.isEmpty() || time.isEmpty() || location.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 连接数据库
        try (Connection conn = dbConnector.connectToDatabase()) {
            if (conn == null) {
                JOptionPane.showMessageDialog(this, "数据库连接失败！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 查询课程是否存在
            String query = "SELECT * FROM user_" + username + " WHERE course_name = ?";
            try (PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setString(1, courseName);
                ResultSet rs = stmt.executeQuery();

                if (!rs.next()) {
                    JOptionPane.showMessageDialog(this, "课程不存在，请检查名称是否正确。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }

            // 更新课程信息
            String updateSQL = "UPDATE user_" + username + " SET teacher_name = ?, time = ?, location = ? WHERE course_name = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateSQL)) {
                updateStmt.setString(1, teacherName);
                updateStmt.setString(2, time);
                updateStmt.setString(3, location);
                updateStmt.setString(4, courseName);

                int rowsAffected = updateStmt.executeUpdate();
                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(this, "课程更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    new choose2(username).setVisible(true);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "更新课程失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库操作失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new modifycourse("exampleUser").setVisible(true));
    }
}
